/*
Version 0.1
*/
YUI.add("ibrpg", function (Y) {
  /* avoid multiple instances */
  if (typeof ibrpg === 'undefined' || !ibrpg) {
	  ibrpg = {
      mydom: document.domain,
      heartbeat: null,
      beforeDialog: null,
      data: {
        visits: 0,
        player: {
          name:"name",
          char_class: "warrior",
          atk: 5,
          def: 5,
          health: 100,
          mana: 100,
          gold: 0,
          xp: 0,
          level: 0,
          inventory: [
            {
              name: "sword",
              atk: 3,
              def: 1
              },
            {
              name: "shield",
              atk: 1,
              def: 4
            }  
          ]
        },
        missions: [
          {
              title: "Getting Started",
              description: "How to play Itty Bitty RPG - and your first mission.",
              details: "Welcome to Itty Bitty RPG! This is a unique RPG where you gain experience points by visiting this site.  Use your skill and weapons to defeat monsters and get gold. Buy bigger weapons and slay even bigger monsters. As you gain experience more missions will unlock. For now, go kill some spiders. Click battle."
          },
          {
            title: "Kill 10 Rats",
            description: "What RPG would be complete without this mission?",
            details: "The storekeeper cannot get to his goods down in the cellar! Help him out by killing 10 giant rats. Once you complete this mission the store will open up"
          }
        ],
        images:{ 
          fighter: {
            name:"fighter",
            src: ""
            },
          wizard: {
             name: "wizard",
             src: ""
           },
           spider : {
             name: "spider",
             src: ""
           },
           helper : {
             name: "helper",
             src: ""
           } 
        }
      },
      getStorage: function(){
        if(window.globalStorage){
          var storage = globalStorage[ibrpg.mydom];
          Y.log(storage);
          if(!storage.ibrpgDATA || storage.ibrpgDATA.value == "null"){
            storage.ibrpgDATA = Y.JSON.stringify(ibrpg.data);
            Y.log(storage);
          } else {
            //Y.log(storage.ibrpgDATA);
            ibrpg.data = Y.JSON.parse(storage.ibrpgDATA.value);
          }
          return true;
        } else {
          return false;
        }
      },
      setStorage: function(){
        if(window.globalStorage){
          var storage = globalStorage[ibrpg.mydom];
          storage.ibrpgDATA = Y.JSON.stringify(ibrpg.data);
          return true;
        }else {
          return false;
        }
      },
      startHeartBeat: function(){
        ibrpg.heartbeat = window.setInterval(ibrpg.beat, 1000);
      },
      stopHeartBeat: function(){
        window.clearInterval(ibrpg.heartbeat);
      },
      beat: function(){
        //Y.log("lubdub...");
        ibrpg.heart.fire("HeartObj:beat"); 
      },
      updateTime:function(){
        var currTime = new Date();

        Y.Node.get(".ibrpg-timer").set('innerHTML', currTime.toTimeString());  
      },
      testSubscribe: function(){
        Y.log("testSubScribe triggered");
      },
      setCharImg: function(imgName){
      Y.log("imgName "+imgName)
      Y.log(ibrpg.data.images)
        Y.Node.get("#ibrpg-char-img").setAttribute("src",ibrpg.data.images[imgName].src);
      },
      showPanel: function(pnl){
          Y.all(".ibrpg-pnl").setStyle("display","none");
          Y.get(pnl).setStyle("display","block");
      },
      saveCharData: function() {
      Y.log(Y.get('#ibrpg-charname').get("value"))

          ibrpg.data.player.name = Y.get('#ibrpg-charname').get("value");
          ibrpg.data.player.xp = Y.get('.ibrpg-xp').get("innerHTML");
          ibrpg.data.player.level = Y.get('.ibrpg-level').get("innerHTML");
          ibrpg.data.player.atk = Y.get('.ibrpg-atk').get("innerHTML");
          ibrpg.data.player.def = Y.get('.ibrpg-def').get("innerHTML");
          ibrpg.data.player.health = Y.get('.ibrpg-health').get("innerHTML");
          ibrpg.data.player.mana = Y.get('.ibrpg-mana').get("innerHTML");
          ibrpg.data.player.gold = Y.get('.ibrpg-gold').get("innerHTML");

          ibrpg.setStorage();
      },
      populateCharPanel: function(){
          Y.get('#ibrpg-charname').set("value",ibrpg.data.player.name);
          Y.get('.ibrpg-xp').set("innerHTML",ibrpg.data.player.xp);
          Y.get('.ibrpg-level').set("innerHTML",ibrpg.data.player.level);
          Y.get('.ibrpg-atk').set("innerHTML",ibrpg.data.player.atk);
          Y.get('.ibrpg-def').set("innerHTML",ibrpg.data.player.def);
          Y.get('.ibrpg-health').set("innerHTML",ibrpg.data.player.health);
          Y.get('.ibrpg-mana').set("innerHTML",ibrpg.data.player.mana);
          Y.get('.ibrpg-gold').set("innerHTML",ibrpg.data.player.gold);
      },
      populateMissionsPanel: function(){
        var missions = ibrpg.data.missions;
        var missionList = Y.get(".ibrpg-missions");
        var missionItems = "";
        for(i=0; i< missions.length; i++){
          missionItems += "<li class='ibrpg-mission-item' id='ibrpg-mission-"+i+"'>"+ missions[i].title+"</li>";
        }
        missionList.set("innerHTML",missionItems);
      },
      init: function () {
        Y.log("ibrpg initted");
        var view = Y.Node.get("#ibrpg");
        //v
         //Y.log(ibrpg.data);
        if(ibrpg.getStorage()){
          ibrpg.data.visits +=1;
          ibrpg.setStorage()
        }
        //Y.log(ibrpg.data);

        /**
        displayTxt = "<div><h3>Welcome to Itty Bitty RPG</h3></div>";
        displayTxt +="<div> You've been here "+ibrpg.data.visits+" times.</div>";
        displayTxt +="<div></div>";
        **/


        displayTxt = "<div>";
        displayTxt += "<div class='ibrpg-panels'>";
        displayTxt += "<div class='ibrpg-start ibrpg-pnl'><h3 style='padding: 0px; margin: 0px;'>Itty Bitty RPG <span class='ibrpg-timer'></span></h3>"
        displayTxt += "<a href='#' id='ibrpg-btn-newgame'>[New Game]</a> <a href='#' id='ibrpg-btn-continue'>[Continue]</a><br/> You've been here "+ibrpg.data.visits +" time(s)"
        displayTxt += "</div>";
        displayTxt += "<div class='ibrpg-char ibrpg-pnl'>";
        displayTxt += "<h3>Your Character <a href='#' id='ibrpg-btn-savedata'>Save Data</a> <a href='#' id='ibrpg-btn-cont-fromchar'>Continue Game</a></h3> ";
        /**
        displayTxt += "<div>name: </div>";
        displayTxt += "<div>class: </div>";
        **/
        displayTxt += "<table>";
        displayTxt += "<tr><td rowspan='2'><img src='' style='height:32px; width: 32px;' id='ibrpg-char-img'/></td><td colspan='3'>NAME: <input type='text' id='ibrpg-charname'/></td></tr>"
        displayTxt += "<tr><td colspan='3'>CLASS: <select id='ibrpg-charselect'><option value='fighter'>Fighter</option> <option value='wizard'>Wizard</option> </select></td></tr>";
        displayTxt += "<tr><td>XP:<span class='ibrpg-xp'>-1</span></td><td>LEVEL: <span class='ibrpg-level'>-1</span></td><td>ATK:<span class='ibrpg-atk'>-1</span></td> <td>DEF:<span class='ibrpg-def'>-1</span></td>        </tr>";
        displayTxt += "<tr><td>HEALTH: <span class='ibrpg-health'>-1</span></td><td>MANA:<span class='ibrpg-mana'>-1</span></td><td>GOLD:<span class='ibrpg-gold'>-1</span></td><td><a href='#' class='ibrpg-char-inventory'>INVENTORY</a></td></tr>";


        displayTxt +="</table>";
        displayTxt += " </div>";
        displayTxt += "<div class='ibrpg-mission ibrpg-pnl'><h3>MISSIONS</h3> <ul class='ibrpg-missions'></ul></div>";
        displayTxt += "<div class='ibrpg-battle ibrpg-pnl'><h3>Battle</h3></div>";
        displayTxt += "<div class='ibrpg-shop ibrpg-pnl'><h3>Shop</h3></div>";
        displayTxt += "<div class='ibrpg-dialog ibrpg-pnl'><div class='ibrpg-close'>x</div><div class='ibrpg-dialog-content'></div></div>";
        displayTxt+= "</div>";

        displayTxt +="</div>";



        view.set("innerHTML", displayTxt);

        /** show the first panel **/
        //Y.Node.get(".ibrpg-start").setStyle("display","block");

        ibrpg.showPanel(".ibrpg-start");

        /** set up heartbeat **/

        ibrpg.HeartObj = function(){
          //create a custom event;
          this.publish("HeartObj:beat");
        }

        Y.augment(ibrpg.HeartObj, Y.Event.Target);

        ibrpg.heart = new ibrpg.HeartObj();
        ibrpg.heart.subscribe("HeartObj:beat",function(){
          //ibrpg.testSubscribe();
          //ibrpg.updateTime()
        });


        /** start heartbeat **/
        ibrpg.startHeartBeat();

        /** show test data url image **/

        ibrpg.setCharImg("fighter");


        /** init character screen **/
        ibrpg.populateCharPanel();

        /** init missions screen **/
        ibrpg.populateMissionsPanel();


        /** attach events to stuff **/
        Y.on('click', function(e){
          Y.log('saving data')
          //ibrpg.setStorage();
          ibrpg.saveCharData();
        }, '#ibrpg-btn-savedata');
        Y.on("click",function(e){
          ibrpg.showPanel(".ibrpg-char");
        }, '#ibrpg-btn-newgame');

        Y.on("change",function(e){

          ibrpg.setCharImg(this.get("value"));
          //Y.log(this.get("value") )
        }, '#ibrpg-charselect');

        Y.on('click',function(e){
          ibrpg.showPanel(".ibrpg-mission");
        }, '#ibrpg-btn-cont-fromchar');

        Y.on('click',function(e){
          ibrpg.beforeDialog = '.ibrpg-mission';
          var theDialog = Y.get('.ibrpg-dialog-content');
          theDialog.set('innerHTML' , ibrpg.data.missions[e.target.get("id").split('ibrpg-mission-')[1]].details );
          ibrpg.showPanel(".ibrpg-dialog");
        }, '.ibrpg-mission-item');
      }
    };
	  
	  
	  
	  
	  
	  
	  
	  /* the rest of the code for the global namespace here ... */
  }
  /* the rest of the code for this module here ... */
  
  
  Y.on("event:ready", function(){
    ibrpg.init();
  });
  
});  
//debugging
//document.body.innerHTML += '<p>module "ibrpg" is ready...</p>';
